package flc.ast.activity;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.stark.cartoonavatarmaker.lib.core.AvatarColorType;
import com.stark.cartoonavatarmaker.lib.core.AvatarConst;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartBean;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartType;
import com.stark.cartoonavatarmaker.lib.core.AvatarRedoUndoController;
import com.stark.cartoonavatarmaker.lib.core.AvatarRole;
import com.stark.cartoonavatarmaker.lib.core.AvatarRoleDbUtil;
import com.stark.cartoonavatarmaker.lib.core.AvatarTemplatePart;
import com.stark.cartoonavatarmaker.lib.core.AvatarUtil;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityDressUpBinding;
import flc.ast.fragment.DressUpColorFragment;
import flc.ast.fragment.DressUpFragment;
import flc.ast.fragment.InfoFragment;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.redo.RedoUndoController;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.view.container.StkLinearLayout;

public class DressUpActivity extends BaseAc<ActivityDressUpBinding> implements RedoUndoController.IListener<AvatarTemplatePart> {

    private List<Fragment> mFragments = new ArrayList<>();
    private List<String> mTitles = new ArrayList<>();
    private Dialog mySaveDialog;
    private AvatarRedoUndoController mRedoUndoController;
    private static AvatarRole sAvatarRole;
    private static String roleName, roleDesc;
    private static long birth;
    private static int position;

    public static void start(@NonNull Context context, @Nullable AvatarRole avatarRole, int pos) {
        Intent intent = IntentUtil.getIntent(context, DressUpActivity.class);
        sAvatarRole = avatarRole;
        position = pos;
        context.startActivity(intent);
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_dress_up;
    }

    @Override
    protected void initView() {
        mDataBinding.ivDressUpBack.setOnClickListener(v -> onBackPressed());

        mRedoUndoController = new AvatarRedoUndoController();
        mRedoUndoController.addListener(this);
        initFragments();
        for (int i = 0; i < mTitles.size(); i++) {
            mDataBinding.tabLayout.addTab(mDataBinding.tabLayout.newTab().setText(mTitles.get(i)));
        }
        mDataBinding.viewPager.setAdapter(new DressUpActivity.MyPagerAdapter(getSupportFragmentManager()));
        mDataBinding.tabLayout.setupWithViewPager(mDataBinding.viewPager);
        //给tab每个item设置值
        for (int i = 0; i < mDataBinding.tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mDataBinding.tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i));
            }
        }
        // 设置默认第一个被选中
        View view = mDataBinding.tabLayout.getTabAt(0).getCustomView();
        TextView tv = view.findViewById(R.id.tvTabItemName);
        tv.setTextColor(Color.parseColor("#230E5B"));
        ImageView iv = view.findViewById(R.id.ivTabItemSel);
        iv.setVisibility(View.VISIBLE);
        //设置TabLayout点击事件
        mDataBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                TextView tv = view.findViewById(R.id.tvTabItemName);
                tv.setTextColor(Color.parseColor("#230E5B"));
                ImageView iv = view.findViewById(R.id.ivTabItemSel);
                iv.setVisibility(View.VISIBLE);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                TextView tv = view.findViewById(R.id.tvTabItemName);
                tv.setTextColor(Color.parseColor("#80230E5B"));
                ImageView iv = view.findViewById(R.id.ivTabItemSel);
                iv.setVisibility(View.GONE);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mDataBinding.tabLayout.getTabAt(position).select();
        checkToShowUndoRedo();
        mDataBinding.ivRedo.setOnClickListener(this);
        mDataBinding.ivUndo.setOnClickListener(this);
        mDataBinding.ivSave.setOnClickListener(this);

        //保存弹框
        saveDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivUndo:
                mRedoUndoController.undo();
                break;
            case R.id.ivRedo:
                mRedoUndoController.redo();
                break;
            case R.id.ivSave:
                if (sAvatarRole == null) {
                    if (TextUtils.isEmpty(roleName)) {
                        ToastUtils.showShort(getString(R.string.please_input_name));
                        mDataBinding.tabLayout.getTabAt(mDataBinding.tabLayout.getTabCount() - 1).select();
                        return;
                    }
                }
                save();
                break;
            //保存弹框
            case R.id.ivDialogSaveCancel://取消
                mySaveDialog.dismiss();
                break;
            case R.id.ivDialogSaveRight://确定
                mySaveDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.avatarMakeView.post(new Runnable() {
            @Override
            public void run() {
                if (sAvatarRole != null) {
                    mDataBinding.avatarMakeView.setTemplatePart(new Gson().fromJson(sAvatarRole.partJson, AvatarTemplatePart.class));
                }
                mRedoUndoController.addDo(mDataBinding.avatarMakeView.getTemplatePart());
            }
        });
    }

    @Override
    public void onDoChanged() {
        checkToShowUndoRedo();
    }

    @Override
    public void onRedo(AvatarTemplatePart value) {
        mDataBinding.avatarMakeView.setTemplatePart(value);
        checkToShowUndoRedo();
    }

    @Override
    public void onUndo(AvatarTemplatePart value) {
        mDataBinding.avatarMakeView.setTemplatePart(value);
        checkToShowUndoRedo();
    }

    private void initFragments() {
        mFragments.clear();
        mTitles.clear();

        for (AvatarPartType type : AvatarPartType.values()) {
            mFragments.add(DressUpFragment.newInstance(type));
            mTitles.add(AvatarConst.getAvatarPartTitle(type));
            if (type == AvatarPartType.body) {
                mFragments.add(DressUpColorFragment.newInstance(AvatarColorType.SKIN));
                mTitles.add(getString(R.string.cam_skin_color));
            } else if (type == AvatarPartType.eyeball) {
                mFragments.add(DressUpColorFragment.newInstance(AvatarColorType.EYE_BALL));
                mTitles.add(getString(R.string.cam_eyeball_color));
            } else if (type == AvatarPartType.hair) {
                mFragments.add(DressUpColorFragment.newInstance(AvatarColorType.HAIR));
                mTitles.add(getString(R.string.cam_hair_color));
            }
        }
        mFragments.add(InfoFragment.newInstance(sAvatarRole));
        mTitles.add(getString(R.string.archives));
    }

    private void checkToShowUndoRedo() {
        if (mRedoUndoController.canUndo()) {
            mDataBinding.ivUndo.setImageResource(R.drawable.icon_ch);
        } else {
            mDataBinding.ivUndo.setImageResource(R.drawable.icon_ch1);
        }
        if (mRedoUndoController.canRedo()) {
            mDataBinding.ivRedo.setImageResource(R.drawable.icon_cz);
        } else {
            mDataBinding.ivRedo.setImageResource(R.drawable.icon_cz1);
        }
    }

    //自定义Tab布局
    private View getTabView(int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab, null);
        TextView text = view.findViewById(R.id.tvTabItemName);
        text.setText(mTitles.get(i));
        text.setTextColor(Color.parseColor("#80230E5B"));
        ImageView image = view.findViewById(R.id.ivTabItemSel);
        image.setVisibility(View.GONE);
        return view;
    }

    public void setAvatarPart(AvatarPartType type, AvatarPartBean partBean) {
        mDataBinding.avatarMakeView.setAvatarPart(type, partBean);
        mRedoUndoController.addDo(mDataBinding.avatarMakeView.getTemplatePart());
    }

    public void setColor(AvatarColorType type, @ColorInt int color) {
        mDataBinding.avatarMakeView.setColor(type, color);
        mRedoUndoController.addDo(mDataBinding.avatarMakeView.getTemplatePart());
    }

    public void setName(String name) {
        if (sAvatarRole != null) {
            sAvatarRole.name = name;
        }
        roleName = name;
    }

    public void setBirth(long time) {
        if (sAvatarRole != null) {
            sAvatarRole.dateOfBirth = time;
        }
        birth = time;
    }

    public void setDesc(String desc) {
        if (sAvatarRole != null) {
            sAvatarRole.desc = desc;
        }
        roleDesc = desc;
    }

    private void save() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO).reqPermissionDesc(getString(R.string.get_save_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                showDialog(getString(com.stark.common.res.R.string.saving));
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.avatarMakeView);
                RxUtil.create(new RxUtil.Callback<Boolean>() {
                    @Override
                    public void doBackground(ObservableEmitter<Boolean> emitter) {
                        Uri uri = FileP2pUtil.saveBitmap2Jpg(mContext, bitmap);
                        if (sAvatarRole == null) {
                            AvatarRole avatarRole = AvatarUtil.createAvatarRole(roleName, birth, roleDesc, FileUtils.getFileName(uri.toString()), uri.toString(), mDataBinding.avatarMakeView.getTemplatePart());
                            AvatarRoleDbUtil.insert(avatarRole);
                        } else {
                            sAvatarRole.imgName = FileUtils.getFileName(uri.toString());
                            sAvatarRole.imgUri = uri.toString();
                            sAvatarRole.partJson = GsonUtils.toJson(mDataBinding.avatarMakeView.getTemplatePart());
                            AvatarRoleDbUtil.update(sAvatarRole);
                        }
                        emitter.onNext(true);
                    }

                    @Override
                    public void accept(Boolean save) {
                        int msgId = com.stark.common.res.R.string.save_failure;
                        if (save) {
                            msgId = R.string.save_success;
                        }
                        ToastUtils.showShort(msgId);
                        dismissDialog();
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }).request();
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(@NonNull FragmentManager fm) {
            super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.get(position);
        }
    }

    //保存弹框
    private void saveDialog() {
        mySaveDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_save, null);
        mySaveDialog.setContentView(inflate);
        mySaveDialog.setCancelable(false);
        Window dialogWindow = mySaveDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogSaveCancel);
        ImageView dialogRight = inflate.findViewById(R.id.ivDialogSaveRight);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
    }

}